﻿using System;
using System.Net;
using System.Text;
using Core.Ndatax.Domain.Dto;
using Core.Ndatax.Infrastructure.Common;
using Core.Ndatax.Infrastructure.Entitys;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Xman.Extensions.Core;

namespace Core.Ndatax.Services
{
    public class ResServer
    {
        private readonly ILogger<ResServer> _logger;
        private readonly UploadOptions _options;
        private readonly HttpClient _client;

        public ResServer(HttpClient client, ILogger<ResServer> logger, IOptions<UploadOptions> options)
        {
            _client = client;
            _logger = logger;
            _options = options.Value;
        }

        public async Task<List<LogUploadRes>> UploadResAsync(List<IBPExamRequestDto> input)
        {
            var result = new List<LogUploadRes>();
            var creates = input.Where(t => t.OperFlag == "4").ToList();
            var updates = input.Where(t => t.OperFlag != "4").ToList();
            _logger.LogInformation($"新增预约状态的申请单个数：{creates.Count}---更新预约状态的申请单个数：{updates.Count}");
            foreach (var item in creates)
            {
                var xml = HL7Helper.CreateIBPAddResXml(item);
                var sendItem = new LogUploadRes { SheetID = item.RequestNo, SendBody = xml, SendTo = _options.AddResUrl };
                var msg = await SendXmlAsync(xml, _options.AddResUrl);
                sendItem.SetResult(msg);
                result.Add(sendItem);
            }
            foreach (var item in updates)
            {
                var xml = HL7Helper.CreateIBPUpdateResXml(item);
                var sendItem = new LogUploadRes { SheetID = item.RequestNo, SendBody = xml, SendTo = _options.UpdateResUrl };
                var msg = await SendXmlAsync(xml, _options.UpdateResUrl);
                sendItem.SetResult(msg);
                result.Add(sendItem);
            }
            return result;
        }

        public async Task UploadCancelResAsync(List<IBPExamRequestDto> input)
        {
            foreach (var item in input)
            {
                var xml = HL7Helper.CreateIBPCancelResXml(item);
                await SendXmlAsync(xml, _options.CancelResUrl);
            }
        }

        public async Task<List<LogUploadRes>> SendResListAsync(List<LogUploadRes> input)
        {
            foreach (LogUploadRes item in input)
            {
                try
                {
                    _logger.LogInformation($"重新发送的参数:{item.SendBody}");
                    var msg = await SendXmlAsync(item.SendBody, item.SendTo);
                    item.SetResult(msg);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"重新发送异常，{ex}");
                    item.SetResult($"重新发送异常，{ex.Message}");
                }
            }
            return input;
        }


        private async Task<string> SendXmlAsync(string xml, string url)
        {
            try
            {
                _logger.LogInformation($"发送的------------：{xml}");
                var sendcontent = new StringContent(xml, Encoding.UTF8, "text/xml");
                sendcontent.Headers.Add("SOAPAction", "http://goodwillcis.com/JHIPLIB.SOAP.BS.HL7V3Service.HIPMessageServer");
                var response = await _client.PostAsync(url, sendcontent);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    _logger.LogError($"Http状态异常，{response.StatusCode}");
                }
                var content = response.Content.ReadAsStringAsync().Result;
                _logger.LogInformation($"收到的------------{content}");
                var element = content.ToXElement().WithoutNamespaces();
                var result = element.ElementPath("acknowledgement").GetAttributeValue("typeCode");
                var msg = result == "AA" ? "发送成功" : element.ElementPath("acknowledgement/acknowledgementDetail/text").Value;
                return msg;
            }
            catch (Exception ex)
            {
                _logger.LogError($"发送失败：{ex}");
                return "发送失败：" + ex.Message;
            }
        }
    }
}
